import {defineStore} from "pinia";
import type {RouteLocationNormalizedLoaded} from "vue-router";
import router from "@/router/index";

export interface TabItem {
  path: string;
  title: string;
  affix: boolean;
}

export const useTabsStore = defineStore("tabs", {
  state: () => ({
    tabs: [] as TabItem[]
  }),
  actions: {
    add(route: RouteLocationNormalizedLoaded) {
      const title = (route.meta?.title as string) || route.name?.toString() || route.path;
      const affix = !!route.meta?.affix;
      if (!this.tabs.find(t => t.path === route.fullPath)) {
        this.tabs.push({ path: route.fullPath, title: title, affix: affix });
      }
    },
    remove(path: string) {
      const index = this.tabs.findIndex(t => t.path === path);
      if (index === -1) return;
      const isCurrent = router.currentRoute.value.fullPath === path;
      this.tabs.splice(index, 1);
      if (isCurrent) {
        let targetTab;
        if (index > 0) {
          targetTab = this.tabs[index - 1];
        } else if (this.tabs.length > 0) {targetTab = this.tabs[0];
        }
        if (targetTab) {
          router.push(targetTab.path);
        } else {
          router.push("/");
        }
      }
    },
    clear() {
      this.tabs = [];
    }
  },
  persist: true
});
